package com.shh.aiojbackendserver.judge.codesandbox.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.shh.aiojbackendserver.common.ErrorCode;
import com.shh.aiojbackendserver.exception.BusinessException;
import com.shh.aiojbackendserver.judge.codesandbox.CodeSandbox;
import com.shh.aiojbackendserver.judge.codesandbox.model.ExecuteCodeRequest;
import com.shh.aiojbackendserver.judge.codesandbox.model.ExecuteCodeResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * 远程代码沙箱 调用接口来实现
 */
@Component
public class RemoteCodeSandbox implements CodeSandbox {
    private static final String AUTH_REQUEST_HEADER = "auth";
    private static final String AUTH_REQUEST_SECRET = "secretKey";

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        String url = "192.168.182.131:8085/executeCode";
        String json = JSONUtil.toJsonStr(executeCodeRequest);
        String responseStr = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEADER,AUTH_REQUEST_SECRET)
                .body(json)
                .execute()
                .body();
        if(StringUtils.isBlank(responseStr)){
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR,"executeCodeRequest api error");
        }
        return JSONUtil.toBean(responseStr,ExecuteCodeResponse.class);
    }
}
